<template>
  <div>
    <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      width="600px"
      :showCancel="false"
      @close="clear"
      :showClose="false"
      :closeOnClickModal="true"
    >
      <el-form
        :model="formData"
        ref="formDataRef"
        label-width="80px"
        @submit.prevent
      >
        <!--展示用户姓名-->
        <el-form-item label="用户呢称" prop="nickName">
          {{ formData.nickName }}
        </el-form-item>

        <el-form-item label="头像" prop="avatar">
          <!-- 头像修改框 -->
          <UpdateAvatar @file="getFile" ref="avatarRef"> </UpdateAvatar>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  getCurrentInstance,
  nextTick,
  useAttrs,
  inject,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import Dialog from "@/components/Dialog.vue";
import { ElMessage } from "element-plus";
import UpdateAvatar from "@/components/UpdateAvatar/updateAvatar.vue";
import { updateAvatar } from "@/api/userinfo";
import { fileToBase64 } from "@/utils/file";

const avatarRef = ref();

const props = defineProps({
  // 显示弹窗
  show: {
    type: Boolean,
    default: false,
  },
  // 弹窗标题
  title: {
    type: String,
    default: "标题",
  },
  // 弹窗内容
  content: {
    type: String,
    default: "内容",
  },
  // actionUrl: {
  //   type: String,
  //   default: "",
  // },
});

const { proxy } = getCurrentInstance();
// 路径参数
const route = useRoute();
//  路由
const router = useRouter();

// 生成表单参数
const formData = ref({});
const formDataRef = ref();
const filedata = ref({});

const dialogConfig = reactive({
  show: false,
  title: props.title,
  buttons: [
    {
      type: "primary",
      text: "确定",
      click: (e) => {
        submitForm();
      },
    },
  ],
});
const emit = defineEmits(["submitForm"]);
// 注入对象
const userInfo = inject("userInfo");

// 弹窗展示的方法
const showUpdateAvatarDialog = (data) => {
  formData.value = Object.assign(data);
  formData.value.avatar = {
    userId: data.userId,
    qqAvatar: data.avatar,
  };
  dialogConfig.show = true;
};
// 获取文件信息
const getFile = (dataForm) => {
  filedata.value.avatar = dataForm.file;
  filedata.value.filename = dataForm.name;
};

// 将文件转换为base64
const Img2Base64 = () => {
  // 将用户信息中的头像信息覆盖
  // fileToBase64(filedata.value.avatar).then((base64String) => {
  //   let ImgBase64 = "data:image/png;base64," + base64String;
  // });
};

// // 清除子组件的文件列表和img
const clear = () => {
  console.log("clear", avatarRef.value);
  avatarRef.value.clearFileList();
  dialogConfig.show = false;
};

// 提交文件
const submitForm = () => {
  console.log("filedata", filedata.value);
  //

  // 如果不是文件类型
  if (!(filedata.value.avatar instanceof File)) {
    ElMessage.error("请上传文件/文件未提交");
    dialogConfig.show = false;
    return;
  }

  // 发送文件 提前加载文件base64编码
  fileToBase64(filedata.value.avatar)
    .then((base64String) => {
      // console.log("base64String.avatar", base64String);
      let Data = new FormData();
      Data.append("file", base64String);
      Data.append("name", filedata.value.filename);
      updateAvatar(Data)
        .then((res) => {
          if (res.code == 200) {
            ElMessage.success("修改成功");
            // console.log("上传后未调用get方法的文件Base64信息:", base64String);
            // 覆盖原cookies
            const userInfoCookies = proxy.VueCookies.get("userInfo");
            delete userInfoCookies.avatar;
            // 删除某个Cookie，只需要新建一个同名的Cookie，并将maxAge设置为0，并添加到response中覆盖原来的Cookie。
            proxy.VueCookies.set("userInfo", userInfoCookies, 0);
            dialogConfig.show = false;
            // console.log(
            //   "上传后未调用get方法的头像Base64信息:",
            //   userInfo.value.avatarurl
            // );
          }
        })
        .catch((err) => {
          ElMessage.error("修改失败");
        });
    })
    .catch((error) => {
      console.error("转换文件为Base64时出错", error);
    });

  setTimeout(() => {
    emit("submitForm");
  }, 200); // 延迟200毫秒（即0.2秒）
};

defineExpose({
  showUpdateAvatarDialog,
});
</script>

<style lang="scss" scoped></style>
